import html2canvas from 'html2canvas';
import { ElLoading, ElMessage } from 'element-plus';
/**
 * 导出生命统计数据为图片
 * @param {Object} data 包含要导出的生命统计数据
 */
export async function exportLifeStatsAsImage(data) {
  // 显示导出中的加载状态
  const loadingInstance = ElLoading.service({
    text: '正在生成图片...',
    background: 'rgba(0, 0, 0, 0.46)'
  });
  try {
    // 创建导出容器
    const exportContainer = document.createElement('div');
    exportContainer.className = 'export-container';
    // 创建导出样式的标题
    const titleElement = document.createElement('div');
    titleElement.className = 'export-title';
    titleElement.innerHTML = `
          <h2>人生漫漫，其修远兮</h2>
          <p class="export-subtitle">此图于 ${new Date().toLocaleDateString()} 生成</p>
          <p class="export-subtitle">向着 ${data.lifeExpectancy} 岁进发,冲啊！！！🏃‍♀️‍➡️</p>
          <div class="export-stat-item">
        <div class="export-stat-label">出生日期</div>
        <div class="export-stat-value">${new Date(data.birthDate).toLocaleDateString()}</div>
          </div>
        `;
    exportContainer.appendChild(titleElement);
    // 复制统计卡片
    const statsElement = document.createElement('div');
    statsElement.className = 'export-stats';
    statsElement.innerHTML = `
      <div class="export-stat-item">
        <div class="export-stat-label">当前年龄</div>
        <div class="export-stat-value">${data.userAge}</div>
      </div>
      <div class="export-stat-item">
        <div class="export-stat-label">已探索世界</div>
        <div class="export-stat-value">${data.lifeStats.percentageLived}%</div>
      </div>
      <div class="export-stat-item">
        <div class="export-stat-label">剩余探索时长</div>
        <div class="export-stat-value">${data.lifeExpectancy - data.userAge}年</div>
      </div>
      <div class="export-stat-item">
        <div class="export-stat-label">剩余探索天数</div>
        <div class="export-stat-value">${data.lifeStats.remainingDays.toLocaleString()}天</div>
      </div>
    `;
    exportContainer.appendChild(statsElement);
    // 修改精确统计数据的布局，添加一个包装容器实现两列布局
    const timeSection = document.createElement('div');
    timeSection.className = 'export-time-section';
    exportContainer.appendChild(timeSection);
    // 左侧时间详情
    const detailsElement = document.createElement('div');
    detailsElement.className = 'export-details';
    detailsElement.innerHTML = `
          <div class="export-details-title">已花费时间</div>
          <div class="export-time-details">
            ${data.lifeTimeDetails.lived.years}年 ${data.lifeTimeDetails.lived.months}月 ${data.lifeTimeDetails.lived.days}天
            ${data.lifeTimeDetails.lived.hours}时 ${data.lifeTimeDetails.lived.minutes}分 ${data.lifeTimeDetails.lived.seconds}秒
          </div>
          <div class="export-details-total">总计: ${data.lifeTimeDetails.totalLivedSeconds.toLocaleString()}秒</div>
          <div class="export-details-title">剩余时间</div>
          <div class="export-time-details">
            ${data.lifeTimeDetails.remaining.years}年 ${data.lifeTimeDetails.remaining.months}月 ${data.lifeTimeDetails.remaining.days}天
            ${data.lifeTimeDetails.remaining.hours}时 ${data.lifeTimeDetails.remaining.minutes}分 ${data.lifeTimeDetails.remaining.seconds}秒
          </div>
          <div class="export-details-total">总计: ${data.lifeTimeDetails.totalRemainingSeconds.toLocaleString()}秒</div>
        `;
    timeSection.appendChild(detailsElement);
    // 右侧添加SVG图形
    const illustrationElement = document.createElement('div');
    illustrationElement.className = 'export-illustration';
    illustrationElement.innerHTML = `
            <svg width="200" height="200" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
                <!-- 生命时钟图形 -->
                <circle cx="50" cy="50" r="45" fill="none" stroke="${data.isDark ? '#7eb9ff' : '#387bff'}" stroke-width="2" />
                <circle cx="50" cy="50" r="40" fill="none" stroke="${data.isDark ? '#e6a23c' : '#d4a017'}" stroke-width="1.5" stroke-dasharray="2,2" />
                <!-- 时钟指针 - 已使用时间百分比决定角度 -->
                <line 
                    x1="50" 
                    y1="50" 
                    x2="${50 + 35 * Math.cos((data.lifeStats.percentageLived / 100 * 2 - 0.5) * Math.PI)}" 
                    y2="${50 + 35 * Math.sin((data.lifeStats.percentageLived / 100 * 2 - 0.5) * Math.PI)}" 
                    stroke="${data.isDark ? '#e6a23c' : '#d4a017'}" 
                    stroke-width="2"
                />
                <!-- 中心点 -->
                <circle cx="50" cy="50" r="3" fill="${data.isDark ? '#7eb9ff' : '#387bff'}" />
                <!-- 时钟刻度 -->
                ${Array.from({ length: 12 }, (_, i) => {
      const angle = (i / 12) * 2 * Math.PI;
      const x1 = 50 + 37 * Math.cos(angle);
      const y1 = 50 + 37 * Math.sin(angle);
      const x2 = 50 + 40 * Math.cos(angle);
      const y2 = 50 + 40 * Math.sin(angle);
      return `<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="${data.isDark ? '#7eb9ff' : '#387bff'}" stroke-width="2" />`;
    }).join('')}
                <!-- 添加文字 -->
                <text x="50" y="30" text-anchor="middle" fill="${data.isDark ? '#e0e0e0' : '#333'}" font-size="5">生命时钟</text>
                <text x="50" y="70" text-anchor="middle" fill="${data.isDark ? '#e0e0e0' : '#333'}" font-size="3.5">已经过 ${data.lifeStats.percentageLived}%</text>
                <!-- 生命飘带 -->
                <path d="M25,85 Q40,65 50,80 T75,70" stroke="${data.isDark ? '#7eb9ff' : '#387bff'}" fill="none" stroke-width="1.5" />
            </svg>
            <div class="export-quote">愿岁月以星河织就温柔<br>光阴以山海酿成壮阔</div>
        `;
    timeSection.appendChild(illustrationElement);
    // 添加进度条
    const progressElement = document.createElement('div');
    progressElement.className = 'export-progress';
    progressElement.innerHTML = `
      <div class="export-progress-title">时光进度条</div>
      <div class="export-progress-bar">
        <div class="export-progress-inner" style="width: ${parseFloat(data.dynamicPercentage)}%"></div>
      </div>
      <div class="export-progress-text">${parseFloat(data.dynamicPercentage).toFixed(6)}%</div>
    `;
    exportContainer.appendChild(progressElement);
    // 添加水印部分，将传入的用户名用于祝福语
    const watermarkElement = document.createElement('div');
    watermarkElement.className = 'export-watermark';
    // 根据是否有用户名来定制祝福语
    const userName = data.userName || '您';
    watermarkElement.textContent = `人生计算器 © ${new Date().getFullYear()} · 祝${userName}平安喜乐🎉`;
    exportContainer.appendChild(watermarkElement);
    // 临时添加到文档中以便转换
    document.body.appendChild(exportContainer);
    // 添加导出样式
    const styleElement = document.createElement('style');
    styleElement.textContent = getExportStyles(data.isDark);
    document.head.appendChild(styleElement);
    // 使用html2canvas将DOM转换为canvas
    const canvas = await html2canvas(exportContainer, {
      backgroundColor: data.isDark ? '#1a2133' : '#f5f7fa',
      scale: 2, // 2x分辨率以获得更清晰的图像
      logging: false,
      useCORS: true,
      allowTaint: true
    });
    // 移除临时添加的元素
    document.body.removeChild(exportContainer);
    document.head.removeChild(styleElement);
    // 将canvas转换为图片并下载
    const imgData = canvas.toDataURL('image/png');
    const link = document.createElement('a');
    link.download = `人生路漫漫.png`;
    link.href = imgData;
    link.click();
    ElMessage.success('图片已成功导出！');
  } catch (error) {
    console.error('导出图片失败:', error);
    ElMessage.error('图片导出失败，请稍后再试');
  } finally {
    // 关闭加载状态
    loadingInstance.close();
  }
}
// 获取导出样式
function getExportStyles(isDark) {
  return `
    .export-container {
      width: 800px;
      padding: 40px;
      background: ${isDark ? '#1a2133' : 'linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%)'};
      color: ${isDark ? '#e0e0e0' : '#333'};
      font-family: Arial, sans-serif;
      border-radius: 20px;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
      position: absolute;
      left: -9999px;
      top: -9999px;
    }
    .export-title {
      text-align: center;
      margin-bottom: 30px;
    }
    .export-title h2 {
      font-size: 32px;
      margin: 0;
      color: ${isDark ? '#7eb9ff' : '#387bff'};
    }
    .export-subtitle {
      margin: 5px 0 0;
      opacity: 0.7;
    }
    .export-stats {
      display: flex;
      justify-content: space-between;
      margin-bottom: 30px;
    }
    .export-stat-item {
      flex: 1;
      text-align: center;
      padding: 20px 10px;
      background: ${isDark ? 'rgba(255,255,255,0.05)' : 'rgba(255,255,255,0.7)'};
      border-radius: 15px;
      margin: 0 10px;
    }
    .export-stat-label {
      font-size: 14px;
      opacity: 0.7;
      margin-bottom: 10px;
    }
    .export-stat-value {
      font-size: 28px;
      font-weight: bold;
      color: ${isDark ? '#7eb9ff' : '#387bff'};
    }
    .export-details-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 10px;
      color: ${isDark ? '#7eb9ff' : '#387bff'};
    }
    .export-time-details {
      font-size: 16px;
      margin-bottom: 10px;
      line-height: 1.6;
    }
    .export-details-total {
      font-weight: bold;
      margin-bottom: 20px;
      color: ${isDark ? '#e6a23c' : '#d4a017'};
    }
    .export-time-section {
      display: flex;
      gap: 20px;
      margin-bottom: 30px;
    }
    .export-details {
      flex: 1;
      background: ${isDark ? 'rgba(255,255,255,0.05)' : 'rgba(255,255,255,0.7)'};
      border-radius: 15px;
      padding: 25px;
    }
    .export-illustration {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background: ${isDark ? 'rgba(255,255,255,0.05)' : 'rgba(255,255,255,0.7)'};
      border-radius: 15px;
      padding: 15px;
    }
    .export-quote {
      text-align: center;
      font-style: italic;
      margin-top: 15px;
      font-size: 14px;
      color: ${isDark ? '#a0a0a0' : '#555'};
      max-width: 200px;
      line-height: 1.5;
    }
    .export-progress {
      background: ${isDark ? 'rgba(255,255,255,0.05)' : 'rgba(255,255,255,0.7)'};
      border-radius: 15px;
      padding: 25px;
    }
    .export-progress-title {
      font-size: 18px;
      margin-bottom: 15px;
      text-align: center;
      font-weight: bold;
    }
    .export-progress-bar {
      height: 20px;
      background: ${isDark ? '#283347' : '#e9e9e9'};
      border-radius: 10px;
      overflow: hidden;
      margin-bottom: 10px;
    }
    .export-progress-inner {
      height: 100%;
      background: ${isDark ? '#7eb9ff' : '#67c23a'};
      border-radius: 10px;
    }
    .export-progress-text {
      text-align: right;
      font-size: 16px;
      font-weight: bold;
    }
    .export-watermark {
      text-align: center;
      opacity: 0.5;
      font-size: 12px;
      margin-top: 30px;
    }
    .export-dialog-content {
      text-align: center;
      padding: 10px 0 20px;
    }
    .dialog-footer {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
  `;
}